/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assisisw.smartcal.webuisubsystem.managedbean.validator;

import assisisw.smartcal.entitysubsystem.IUserController;
import assisisw.smartcal.securitysubsystem.IMailVerifier;
import java.util.Objects;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Francesco
 */
public abstract class AbstractUserNameValidator implements Validator
{
    
    // Static Fields
    
    /***/
    private static final FacesMessage wrongUsernameFormatMessage = new FacesMessage ( "Bad format for an e-mail!" ) ;
    
    /***/
    private static final FacesMessage usernameRequiredMessage = new FacesMessage ( "Userame is a required field !" ) ;

    /***/
    private static final FacesMessage usernameTooLongMessage = new FacesMessage ( "Sorry, too long !" ) ;
    
    /***/
    private static final int MAX_SIZE = 20 ;
    
    // Instance Fields
        
    /***/
    @EJB
    private IMailVerifier mailVerifier ;
    
    /***/
    @EJB
    private IUserController userController ;
    
    // Instance Methods
    
    /***/
    protected AbstractUserNameValidator () {}
    
    /**
     * @param mail
     */
    protected abstract void specificValidation ( String mail ) throws ValidatorException ;
    
    /**
     * AS THE SUPER'S ONE.
     */
    @Override
    public void validate( FacesContext context, UIComponent component, Object value) throws ValidatorException  
    {
        String mail ;
        if ( Objects.nonNull ( value ) && ! value.toString().isEmpty () )
        {
            mail = value.toString () ;
            if ( mailVerifier.isStaticallyOk ( mail ) )
                if ( mail.length() <= MAX_SIZE )
                    specificValidation ( value.toString () ) ;
                else
                    throw new ValidatorException ( usernameTooLongMessage ) ;
            else
                throw new ValidatorException ( wrongUsernameFormatMessage ) ;
        }
        else
            throw new ValidatorException ( usernameRequiredMessage ) ;
    }
    
    /**
     * @return
     */
    protected IMailVerifier getMailVerifier () 
    {
        return mailVerifier ;
    }
    
    /**
     * @return
     */
    protected IUserController getUserController () 
    {
        return userController ;
    }
    
}
